<?php
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: konakona
// | Date: {13-5-24}{上午10:10}
// | Version: $Id$
// +---------------------------------------------------------------------- 
class OrderSuccess {

    /**
     * 更改相关内容
     * @param $data
     *
     * @return boolean
     */
    public static function update( $data ) {
        $creditsRatio  = M( 'Options' )->where( array( 'key' => 'credits_ratio' ) )->getField( 'value' );
        $shopCartModel = D( 'Admin/ShopCart' );
        try {
            $shopCart   = $shopCartModel->getCartList( $data[ 'id' ] );
            $totalPrice = $shopCartModel->getTotalPrice( $shopCart );

            foreach ( $shopCart as $k => $v ) {
                //增加商品销量，减少商品库存
                D( 'Home/Shop' )->addSaleNum( $v[ 'shop_id' ] , $v[ 'num' ] );
                D( 'Home/Shop' )->incNum( $v[ 'shop_id' ] , $v[ 'num' ] );
                //增加会员的积分
                D( 'Home/Member' )->addCredits( $v[ 'uid' ] , $totalPrice , $creditsRatio );
                //增加等级值
                D( 'Home/Member' )->addLevelVal( $v[ 'uid' ] , $totalPrice );
            }
        } catch ( Exception $e ) {
            return false;
        }
        return true;
    }

    public static function run() {
        //每个3分钟执行一次
        if ( $_SESSION[ 'orderSuccessTime' ] ) {
            if ( ( time() - $_SESSION[ 'orderSuccessTime' ] ) < 180 ) {
                return;
            }
        } else {
            $_SESSION[ 'orderSuccessTime' ] = time();
        }
        $sec = 1800; //30分钟
        //所有未指定和指定发货时间的发货中订单
        $orders = D( 'Order' )->where( 'status=0 AND ((delivery_time = 0 AND now()-add_time > ' . $sec . ') OR  (delivery_time > 0 AND now()-delivery_time > ' . $sec . '))' )->select();

        /**
         * 记录需要修改状态的订单id
         */
        $updateIDs = array();

        if ( $orders ) {
            foreach ( $orders as $k => $v ) {
                if ( false !== self::update( $v ) ) $updateIDs[ ] = $v[ 'id' ];
            }

            D( 'Order' )->where( 'id IN (' . implode( ',' , $updateIDs ) . ')' )->setField( 'status' , 1 );

        }
    }
}
